package com.superb.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.common.core.annotation.SuperbDataScope;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.model.Result;
import com.superb.common.database.vo.BatchId;
import com.superb.common.database.vo.PageParams;
import com.superb.common.utils.HeardersUtils;
import com.superb.common.utils.StringUtils;
import com.superb.system.api.entity.SystemPermission;
import com.superb.system.api.entity.SystemRole;
import com.superb.system.service.SystemPermissionService;
import com.superb.system.service.SystemRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * 系统角色;(system_role)表控制层
 * @Author: ajie
 * @CreateTime: 2024-6-3
 */
@SuperbDataScope
@SuperbRestMapping("/systemRole")
@Tag(name = "系统角色接口")
@ApiSupport(author = "阿杰：ajie20999@163.com", order = 4)
public class SystemRoleController {

    @Resource
    private SystemRoleService systemRoleService;
    @Resource
    private SystemPermissionService permissionService;

    @PostMapping("pageQuery")
    @ApiOperationSupport(order = 1)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "分页查询", description = "权限: system:role:manage<br>")
    public Result<Page<SystemRole>> pageQuery(@RequestBody PageParams<SystemRole> pageParams) {
        SystemRole params = pageParams.getParams();
        LambdaQueryWrapper<SystemRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(params.getName()), SystemRole::getName, params.getName());
        lqw.like(StringUtils.isNotBlank(params.getCode()), SystemRole::getCode, params.getCode());
        if (StringUtils.isNotBlank(params.getOrganId())) {
            lqw.eq(SystemRole::getOrganId, params.getOrganId());
        } else {
            lqw.and(l -> l.eq(SystemRole::getOrganId, "").or().isNull(SystemRole::getOrganId));
        }
        lqw.orderByAsc(SystemRole::getSort);
        Page<SystemRole> result = systemRoleService.page(pageParams.getPage(), lqw);
        return Result.success(result);
    }

    @PostMapping("insert")
    @ApiOperationSupport(order = 2)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "新增信息", description = "权限: system:role:manage<br>")
    public Result<Boolean> insert(@RequestBody @Validated SystemRole systemRole) {
        // 系统角色则不存在部门
        if (systemRole.getType() == 0) {
            systemRole.setOrganId("");
        }
        if (systemRoleService.save(systemRole)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("update")
    @ApiOperationSupport(order = 3)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "修改信息", description = "权限: system:role:manage<br>")
    public Result<Boolean> update(@RequestBody @Validated SystemRole systemRole) {
        if (systemRoleService.updateById(systemRole)) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("info/{id}")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "根据id获取信息", parameters = {
            @Parameter(name = "id", description = "业务主键", required = true, in = ParameterIn.PATH)
    })
    public Result<SystemRole> getInfo(@PathVariable String id) {
        return Result.success(systemRoleService.getById(id));
    }

    @GetMapping("remove/{id}")
    @ApiOperationSupport(order = 5)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "根据id删除", description = "权限: system:role:manage<br><font style='color: #1890FF'>假删除，会进入回收站</font>", parameters = {
            @Parameter(name = "id", description = "业务主键", required = true, in = ParameterIn.PATH)
    })
    public Result<Boolean> removeById(@PathVariable String id) {
        if (systemRoleService.update(Wrappers.<SystemRole>lambdaUpdate().set(SystemRole::getDel, 1).eq(SystemRole::getId, id))) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("delQuery")
    @ApiOperationSupport(order = 6)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "回收站", description = "权限: <br>system:role:manage")
    public Result<List<SystemRole>> delQuery() {
        List<SystemRole> result = systemRoleService.delPage();
        return Result.success(result);
    }

    @PostMapping("recovery")
    @ApiOperationSupport(order = 7)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "根据id恢复删除的数据", description = "权限: <br>system:role:manage")
    public Result<Boolean> recovery(@RequestBody @Validated BatchId batchId) {
        if (systemRoleService.recoveryByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("delete")
    @ApiOperationSupport(order = 8)
    @SaCheckPermission(value = {"system:role:manage"}, mode = SaMode.OR)
    @Operation(summary = "根据id彻底删除", description = "权限: system:role:manage<br><font style='color: red'>真删除，数据无法恢复</font>")
    public Result<Boolean> delete(@RequestBody @Validated BatchId batchId) {
        if (systemRoleService.deleteByBatchId(batchId.getId())) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("menuPermission/{type}")
    @ApiOperationSupport(order = 9)
    @SaCheckPermission("system:menu:select")
    @Operation(summary = "菜单权限查询", description = "权限: system:menu:select<br>", parameters = {
            @Parameter(name = "type", description = "菜单类型：0侧边栏菜单；1顶部菜单；2中台菜单", required = true)
    })
    public Result<List<SystemPermission>> query(@PathVariable String type) {
        List<SystemPermission> result = permissionService.menuTree(type, true);
        return Result.success(result);
    }

    @GetMapping("systemList")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "系统角色列表项")
    public Result<List<SystemRole>> systemList() {
        LambdaQueryWrapper<SystemRole> lqw = new LambdaQueryWrapper<>();
        // 系统角色
        lqw.and(l -> l.eq(SystemRole::getOrganId, "").or().isNull(SystemRole::getOrganId));
        lqw.eq(SystemRole::getTenantId, HeardersUtils.getTenantId());
        lqw.orderByAsc(SystemRole::getSort);
        List<SystemRole> result = systemRoleService.list(lqw);
        return Result.success(result);
    }
}